<?php


namespace app\wechat\controller;


use app\BaseController;
use app\common\model\Order;
use app\common\model\Finance;
use app\common\model\User;
use think\cache\driver\Redis;
use think\facade\Cache;
use think\facade\Db;
use think\exception\ValidateException;
class Admin extends AuthBase
{
     protected $noLogin = ['teacher_major_list','finance_index'];
     public function teacher_major_list(){
         $sql = "SELECT major_one AS value FROM bingdi_user 
        UNION 
        SELECT major_two AS value FROM bingdi_user 
        UNION 
        SELECT major_three AS value FROM bingdi_user";

// 执行查询并提取一维数组
         $result = Db::query($sql);
         $values = array_column($result, 'value');
         return $this->show(1,'',$values);
         $list=Db::name('user')
             ->distinct(true)
             ->where(['type'=>4])
             ->field('major_one,major_two,major_three')
             ->select();
         return $this->show(1,'',$list);
         $list=array_column($list,'major_one');
     }
        /**\
     * @return \think\response\Json
     * 财务列表
     */
    public function finance_teacher_index()
    {
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        $search = input('param.search');
        $where=[];
        if($search){
            $where[] = [
                'f.order_no|u.nickname', 'like',  "%".$search."%"
            ];
        }
        $where[] = [
            'f.status', '=',  2
        ];
        $where[] = [
            'f.type', '=',  3
        ];
        $model = Finance::where($where)
            ->alias('f')
            ->leftJoin('user u','f.teacher_id=u.id')
            ->leftJoin('order o','f.order_id=o.id')
            ->order('f.create_time DESC')
            ->page($page, $limit)
            ->column('f.id,u.nickname,u.head_img,u.id,f.price,f.teacher_id,o.teacher_yet_price');
        $count = Finance::where($where)
            ->alias('f')
            ->leftJoin('user u','f.teacher_id=u.id')
            ->leftJoin('order o','f.order_id=o.id')
            ->count();
        $data['yet_price']=0;
        foreach($model as $k=>$v){
            $data['yet_price']+=$v['teacher_yet_price'];
        }
        //计算总数
        $data['total_price'] = Finance::where(['status'=>2,'type'=>3])
            ->sum('price');
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
        /**\
     * @return \think\response\Json
     * 订单列表
     */
    public function order_index()
    {
        $type = input('get.type');
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 20, 'intval');
        $search = input('param.search');
        $where=[];
        if($search){
            $where[] = [
                'o.order_no|u.nickname', 'like',  "%".$search."%"
            ];
        }
        $where[] = [
            'o.type', '=',  $type
        ];
        $where[]=[
            'o.status',"in",[2,3,4,5,6,7,8,9]
        ];
        $model = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.teacher_id=u.id')
            ->order('o.clock_date DESC')
            ->page($page, $limit)
            ->column('o.id,o.order_no,o.name,o.send_price,o.software_ask_one,o.software_ask_two,
            o.software_ask_three,u.head_img,u.nickname,o.teacher_price,o.type,o.status,o.clock_date,o.teacher_id,o.middle_date,o.end_date');
        foreach ($model as $key => $value) {
            //已结款
            $model[$key]['yet_send_price'] = Db::name('finance')->where(['order_id'=>$value['id'],'type'=>2,'status'=>4])->sum('price');
            //老师已结款
            $model[$key]['teacher_yet_price'] = Db::name('finance')
            ->where(['order_id'=>$value['id'],'type'=>3,'status'=>4,'teacher_id'=>$value['teacher_id']])->sum('price');
            if($value['clock_date']){
                $model[$key]['clock_date'] = date('Y-m-d',$value['clock_date']);
                if($value['clock_date']<time()){
                    $model[$key]['biaohong']=1;
                }
            }else{
                $model[$key]['biaohong'] = 2;
            }
        }
        $count = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.teacher_id=u.id')
            ->count();
        $data['total_price']=Db::name('order')
            ->where(['type'=>$type])
            ->where('status','in',[2,3,4,5,6,7,8,9])
            ->sum('send_price');
        $data['total_yet_price']=Db::name('finance')->where(['type'=>2,'status'=>4])->sum('price');
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
    /**\
     * @return \think\response\Json
     * 订单列表
     */
    public function teacher_index()
    {
        $major = input('get.type');
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        $search = input('param.search');
        $where=[];
        if($search){
            $where[] = [
                'nickname', 'like',  "%".$search."%"
            ];
        }
        if ($major){
            $where[] = [
                'major_one|major_two|major_three', '=',  $major
            ];
        }
        $where[]=[
            'type','=',4
        ];
        $model = User::where($where)
            ->order('create_time DESC')
            ->page($page, $limit)
            ->column('id,nickname,head_img,major_one,major_two,major_three,strong_point,teacher_status');
        foreach ($model as $key => $value) {
            $model[$key]['one'] = Db::name('order')->where(['teacher_id'=>$value['id'],'status'=>2])->count();
            $model[$key]['two'] = Db::name('order')->where(['teacher_id'=>$value['id'],'status'=>[4,5,6,7]])->count();
            $model[$key]['three'] = Db::name('order')->where(['teacher_id'=>$value['id'],'status'=>8])->count();
        }
        $count = User::where($where)
            ->count();
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
    /**\
     * @return \think\response\Json
     * 订单列表
     */
    public function teacher_list()
    {
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        $search = input('param.search');
        $where=[];
        if($search){
            $where[] = [
                'nickname', 'like',  "%".$search."%"
            ];
        }
        $where[]=[
            'type','=',4
        ];
        $model = User::where($where)
            ->order('create_time DESC')
            ->page($page, $limit)
            ->column('id,nickname,head_img');
        $count = User::where($where)
            ->count();
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
    /**
     * 老师详情
     */
    public function teacher_info(){
        $id=input('get.id');
        $model=Db::name('user')
            ->where('id',$id)
            ->find();
        $model['one'] = Db::name('order')->where(['teacher_id'=>$model['id'],'status'=>2])->count();
        $model['two'] = Db::name('order')->where(['teacher_id'=>$model['id'],'status'=>[4,5,6,7]])->count();
        $model['three'] = Db::name('order')->where(['teacher_id'=>$model['id'],'status'=>8])->count();
        $model['total_order_price_gong']=Db::name('order')
            ->where(['teacher_id'=>$id,'type'=>1])
            ->where('status','<>',10)
            ->sum('teacher_price');
        $model['total_order_price_wen']=Db::name('order')
            ->where(['teacher_id'=>$id,'type'=>2])
            ->where('status','<>',10)
            ->sum('teacher_price');
        $model['order_num_gong']=Db::name('order')
            ->where(['teacher_id'=>$id,'type'=>1])
            ->where('status','<>',10)
            ->count();
        $model['order_num_wen']=Db::name('order')
            ->where(['teacher_id'=>$id,'type'=>2])
            ->where('status','<>',10)
            ->count();
        $order_id_gong=Db::name('order')
            ->where(['teacher_id'=>$id,'type'=>1])
            ->where('status','<>',10)
            ->column('id');
        $order_id_wen=Db::name('order')
            ->where(['teacher_id'=>$id,'type'=>2])
            ->where('status','<>',10)
            ->column('id');
        $model['yet_price_gong']=Db::name('finance')
            ->where(['order_id'=>$order_id_gong,'type'=>3,'status'=>4])
            ->sum('price');
        $model['yet_price_wen']=Db::name('finance')
            ->where(['order_id'=>$order_id_wen,'type'=>3,'status'=>4])
            ->sum('price');
        return $this->show(1,'',$model);
    }
    /**
     * 修改老师信息
     */
    public function edit_teacher_info(){
        $data=input('post.');
        Db::startTrans();
        try {
            //把所有订单改为结算中
            Db::name('user')->where(['id'=>$data['id'],'type'=>4])->update($data);
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    /**\
     * @return \think\response\Json
     * 订单列表
     */
    public function await_order()
    {
        $type = input('get.type');
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        $search = input('param.search');
        $where=[];
        if($search){
            $where[] = [
                'o.order_no|u.nickname', 'like',  "%".$search."%"
            ];
        }
        $where[] = [
            'o.type', '=',  $type
        ];
        $where[]=[
            'o.status','=',1
        ];
        $model = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.student_id=u.id')
            ->order('o.create_time DESC')
            ->page($page, $limit)
            ->column('o.id,o.type,o.send_price,o.order_no,o.name,o.software_ask_one,o.software_ask_two,o.software_ask_three');
        $count = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.student_id=u.id')
            ->count();
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
    /**
     * 派单
     */
    public function send_order(){
        $data=input('post.');
        Db::startTrans();
        $order=Db::name('order')
            ->where(['id'=>$data['id'],'status'=>1])
            ->lock()
            ->find();
        if (!$order){
            return show(0,'当前订单状态已改变');
        }
        if ($order['send_price']<$data['price']){
            return show(0,'老师价格不能大于本价格');
        }
        try {
            //修改订单信息
            Db::name('order')->where(['id'=>$data['id']])->update(['status'=>2,'teacher_id'=>$data['teacher_id'],
                'teacher_price'=>$data['price'],'clock_date'=>strtotime($data['clock_date'])
            ]);
            //添加消息记录
            $message[0]="专业: ".$order['major'];
            $message[1]="软件要求: ".$order['software_ask_one'].$order['software_ask_two'].$order['software_ask_three'];
            Db::name('message')
                ->insert(['student_id'=>$order['student_id'],'teacher_id'=>$data['teacher_id'],'order_id'=>$data['id'],
                    'create_time'=>time(),'update_time'=>time(),'count'=>2,'content'=>json_encode($message),'status'=>2]);
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    /**\
     * @return \think\response\Json
     * 退单列表
     */
    public function order_cancel_index()
    {
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        $search = input('param.search');
        $where=[];
        if($search){
            $where[] = [
                'o.order_no|u.nickname', 'like',  "%".$search."%"
            ];
        }
        $where[] = [
            'o.status', '=',  10
        ];
        $model = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.student_id=u.id')
            ->order('o.create_time DESC')
            ->page($page, $limit)
            ->column('o.id,o.price,o.order_no,o.name,o.status,o.send_price');
        foreach ($model as $key => $value) {
            $model[$key]['yet_send_price'] = Db::name('finance')->where(['order_id'=>$value['id'],'type'=>2,'status'=>4])->sum('price');
            $model[$key]['xu_send_price'] = Db::name('finance')->where(['order_id'=>$value['id'],'type'=>2,'status'=>[2,3]])->sum('price');
        }
        $count = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.student_id=u.id')
            ->count();
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
    /**
     * 学生信息列表
     */
    public function student_index()
    {
        $type = input('get.type');
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        $search = input('param.search');
        $where=[];
        if($search){
            $where[] = [
                'o.order_no|u.nickname', 'like',  "%".$search."%"
            ];
        }
        $where[] = [
            'o.type', '=',  $type
        ];
        $model = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.student_id=u.id')
            ->order('o.create_time DESC')
            ->page($page, $limit)
            ->column('o.id,u.nickname,u.id,u.head_img,o.price,o.yet_price,o.order_no,o.name,o.status');
        $count = Order::where($where)
            ->alias('o')
            ->leftJoin('user u','o.student_id=u.id')
            ->count();
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
    /**\
     * @return \think\response\Json
     * 财务列表
     */
    public function finance_index()
    {
        $page = input('param.page', 1, 'intval');
        $limit = input('param.limit', 50, 'intval');
        $pay=Db::name('finance_pay')->where(['status'=>1])->value('ids');
        $id=explode(",",$pay);

        $model = Finance::where(["f.id"=>$id])
            ->alias('f')
            ->leftJoin('order o','f.order_id=o.id')
            ->order('f.create_time DESC')
            ->page($page, $limit)
            ->column('o.id,o.order_no,o.name,o.status,o.price as order_price,o.send_price,f.price,f.order_status');
        $data['total_yet_send_price']=0;
        foreach ($model as $key => $value) {
            $total=Db::name('finance')->where(['order_id'=>$value['id'],'type'=>2,'status'=>4])->sum('price');
            $data['total_yet_send_price']+=$total;
            $model[$key]['yet_send_price'] = $total;
        }
        $count = Finance::where(["f.id"=>$id])
            ->alias('f')
            ->leftJoin('order o','o.id=f.order_id')
            ->count();
        //计算总数
//        $data['total_yet_send_price']=Finance::where(['status'=>2,'type'=>4,'id'=>$id])
//            ->sum('price');;
        $data['total_price'] = Finance::where(['status'=>3,'type'=>2,'id'=>$id])
            ->sum('price');
        $data['total'] = $count;
        $data['list'] = $model;
        $data['page'] = $page;
        return $this->show(1, '', $data);
    }
    /**
     * 财务结款
     */
    public function finance_pay(){
        //判断是否可以
        $res=Db::name('finance_pay')->where('status',1)->lock()->find();
        if(!$res){
            return $this->show(0,'状态不对');
        }
        //找到所有结算中的订单
        $finance=Db::name('finance')->where(['status'=>2,'type'=>3])->column('id');
        Db::startTrans();
        try {
            //把所有订单改为已结算
            Db::name('finance')->where(['status'=>3,'type'=>2])->update(['status'=>4]);
            Db::name('finance_pay')
                ->where(['id'=>$res['id']])
                ->update(['status'=>2,'affirm_time'=>time()]);
            Db::commit();
            return show(1, '确认成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    /**
     * 消息列表
     */
    public function message_index()
    {
         $type=input('get.type');
         $where[]=[
            'type','=',$type
         ];
         $message=Db::name('message')
         ->alias('m')
         ->leftJoin('order o','o.id=m.order_id')
         ->where(['m.type'=>$type,'m.status'=>1])
         ->column('m.id,o.order_no,o.name,m.count,o.type,o.status,m.content');
         foreach ($message as $key => $value) {
             $message[$key]['content']=json_decode($value['content'],true);
         }
         return show(1,'',$message);
    }
    /**
     * 转发消息
     */
    public function affirm_message(){
        $data=input('post.');
        $message=Db::name('message')->where(['id'=>$data['id'],'status'=>1])->lock()->find();
        $order=Db::name('order')->where(['id'=>$message['order_id']])->find();
        if(!$message){
            return show(0,'消息已处理');
        }
        Db::startTrans();
        try {
            //修改消息状态和内容
            Db::name('message')->where(['id'=>$data['id']])->update(['status'=>2,'content'=>json_encode($data['content'])]);
            //如果订单状态是初稿那就给老师结款等信息
            if($order['status']==2){
                //修改订单状态
                Db::name('order')->where(['id'=>$message['order_id']])->update(['status'=>3]);
                //给老师结款,记录到表里,给百分之40的钱
                Db::name('finance')->insert([
                    'order_id'=>$message['order_id'],
                    'name'=>"给老师定稿的钱",
                    'price'=>round($order['teacher_price']*0.4,2),
                    'status'=>2,
                    'type'=>3,
                    'teacher_id'=>$order['teacher_id'],
                    'create_time'=>time(),
                    'update_time'=>time()
                ]);
                //给管理员结款记录,百分之40
                Db::name('finance')
                    ->insert(['name'=>"初稿结算给管理员",'status'=>2,'order_id'=>$order['id'],
                    'price'=>round($order['send_price']*0.4,2),'type'=>2,'order_status'=>2,
                    'create_time'=>time(),'update_time'=>time()]);
            }else if($order['status']==3 && $message['type']==2){
                //如果已经是初稿状态,那就给改成修改1状态
                Db::name('order')->where(['id'=>$message['order_id']])->update(['status'=>4]);
            }else if($order['status']==4 && $message['type']==2){
                //如果已经是修改一状态改成修改2
                Db::name('order')->where(['id'=>$message['order_id']])->update(['status'=>5]);
            }
            else if($order['status']==5 && $message['type']==2){
                //如果已经是修改二状态改成修改3
                Db::name('order')->where(['id'=>$message['order_id']])->update(['status'=>6]);
            }else if($order['status']==6 && $message['type']==2){
                //如果已经是修改三状态改成修改4
                Db::name('order')->where(['id'=>$message['order_id']])->update(['status'=>7]);
                //并且给老师钱
                Db::name('finance')->insert([
                    'order_id'=>$message['order_id'],
                    'name'=>"修改4次",
                    'price'=>round($order['teacher_price']*0.4,2),
                    'status'=>2,
                    'type'=>3,
                    'teacher_id'=>$order['teacher_id'],
                    'create_time'=>time(),
                    'update_time'=>time()
                ]);
            }else if($order['status']==7 && $message['type']==2){
                //如果已经是修改三状态改成修改4
                Db::name('order')->where(['id'=>$message['order_id']])->update(['status'=>8]);
                //并且给老师钱0.2
                Db::name('finance')->insert([
                    'order_id'=>$message['order_id'],
                    'name'=>"定稿",
                    'price'=>round($order['teacher_price']*0.2,2),
                    'status'=>2,
                    'type'=>3,
                    'teacher_id'=>$order['teacher_id'],
                    'create_time'=>time(),
                    'update_time'=>time()
                ]);
                 //给管理员结款记录,百分之30
                Db::name('finance')
                    ->insert(['name'=>"定稿结算给管理员",'status'=>2,'order_id'=>$order['id'],
                    'price'=>round($order['send_price']*0.3,2),'type'=>2,'order_status'=>3,
                    'create_time'=>time(),'update_time'=>time()]);
            }
            Db::commit();
            return show(1, '转发成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
        /**
     * 管理员给老师结款
     */
    public function finance_teacher_pay(){
        //判断是否可以
        $res=Db::name('finance')->where(['status'=>2,'type'=>3])->select()->toArray();
        if(!$res){
            return $this->show(0,'状态不对');
        }
        Db::startTrans();
        try {
            //把所有订单改为已结算
            Db::name('finance')->where(['status'=>2,'type'=>3])->update(['status'=>4]);
            //给所有订单增加老师已结款
            foreach ($res as $k=>$v){ 
                Db::name('order')
                ->where(['id'=>$v['order_id']])
                ->inc('teacher_yet_price',$v['price'])
                ->update();
            }
            Db::commit();
            return show(1, '结款成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    /**
     * 数据统计
     */
    public function finance_statistics(){
        $gong_order_id=Db::name('order')
            ->where(['type'=>1,'status'=>[1,2,3,4,5,6,7,8,9]])
            ->column('id');
        $wen_order_id=Db::name('order')
            ->where(['type'=>2,'status'=>[1,2,3,4,5,6,7,8,9]])
            ->column('id');
        $yanhui['gong_order_price']=Db::name('order')->where(['id'=>$gong_order_id])->sum('send_price');
        $yanhui['wen_order_price']=Db::name('order')->where(['id'=>$wen_order_id])->sum('send_price');
        $yanhui['gong_order_num']=Db::name('order')->where(['id'=>$gong_order_id])->count();
        $yanhui['wen_order_num']=Db::name('order')->where(['id'=>$wen_order_id])->count();
        $yanhui['gong_yet_price']=Db::name('finance')->where(['order_id'=>$gong_order_id,'status'=>4,'type'=>2])->sum('price');
        $yanhui['wen_yet_price']=Db::name('finance')->where(['order_id'=>$wen_order_id,'status'=>4,'type'=>2])->sum('price');
        

        //工资支出
        $gongzi['gong_order_price']=Db::name('order')->where(['id'=>$gong_order_id])->sum('teacher_price');
        $gongzi['wen_order_price']=Db::name('order')->where(['id'=>$wen_order_id])->sum('teacher_price');
        $gongzi['gong_order_num']=Db::name('order')->where(['id'=>$gong_order_id])->count();
        $gongzi['wen_order_num']=Db::name('order')->where(['id'=>$wen_order_id])->count();
        $gongzi['gong_yet_price']=Db::name('finance')->where(['order_id'=>$gong_order_id,'status'=>4,'type'=>3])->sum('price');
        $gongzi['wen_yet_price']=Db::name('finance')->where(['order_id'=>$wen_order_id,'status'=>4,'type'=>3])->sum('price');
        $data['yanhui']=$yanhui;
        $data['gongzi']=$gongzi;
        return show(1,'',$data);
    }
    /**
     * 转派
     */
    public function again_send_order(){
        $data=input('post.');
        Db::startTrans();
        $order=Db::name('order')
            ->where(['id'=>$data['id'],'status'=>[2,3,4,5,6,7,8]])
            ->lock()
            ->find();
        if (!$order){
            return show(0,'当前订单状态无法转派');
        }
        try {
            //修改订单信息
            Db::name('order')->where(['id'=>$data['id']])->update(['teacher_id'=>$data['teacher_id'],
                'teacher_price'=>$data['price'],'clock_date'=>strtotime($data['clock_date']),'teacher_yet_price'=>0
            ]);
            //删除带结算和结算中信息
            Db::name('finance')->where(['order_id'=>$data['id'],'teacher_id'=>$order['teacher_id'],'type'=>3,'status'=>[2,3]])->delete();
            //修改消息接收人
            Db::name('message')
                ->where(['teacher_id'=>$order['teacher_id'],'order_id'=>$data['id']])
                ->update(['teacher_id'=>$data['teacher_id']]);
            Db::commit();
            return show(1, '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return show(0, $e->getMessage());
        }
    }
    public function edit_clock(){
        $data=input('post.');
        $res=Db::name('order')
            ->where('id',$data['id'])
            ->update(['clock_date'=>strtotime($data['clock_date'])]);
        if ($res){
            return $this->show(1,'修改成功');
        }
        return $this->show(0,'修改失败');
    }
}
